import coin.exchange.base.kr_rest.private_client_base as privcb
import coin.exchange.bitfinex_v1.kr_rest.native_private_client as nprivc

from coin.proto.coin_query_pb2 import (AccountBalance,
                                       CurrencyBalance,
                                       ProductFillElement,
                                       ProductFillBundle)


class BitfinexPrivateParser(object):
  @staticmethod
  def parse_balance(update_msg_list: list):
    currency_balance_list = []
    for update_msg in update_msg_list:
      currency_balance = CurrencyBalance(
          currency=update_msg['currency'].upper(),
          currency_native=update_msg['currency'],
          total=float(update_msg['amount']),
          available=float(update_msg['available']),
      )
      currency_balance_list.append(currency_balance)

    return AccountBalance(exchange='Bitfinex', each_balance=currency_balance_list)


class BitfinexPrivateClient(privcb.PrivateClientBase):
  def __init__(self, key_file):
    privcb.PrivateClientBase.__init__(self)
    self.nprivc = nprivc.BitfinexNativePrivateClient(key_file=key_file)

  def query_account_balance_impl(self):
    update = self.nprivc.query_balances()
    update.msg = BitfinexPrivateParser.parse_balance(update.msg)
    return update

  def query_fills_impl(self, product):
    raise NotImplementedError()

  def query_submit_impl(self, product, side, price, qty):
    symbol = product.native_symbol
    update = self.nprivc.query_order_new(symbol, side, price, qty, "exchange limit")
    return update

  def query_cancel_product_impl(self, product):
    symbol = product.native_symbol
    update = self.nprivc.query_order_cancel_all()
    return update
